package org.jvending.provisioning.portal;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.IOException;
import java.util.logging.Logger;

public class SearchCatalogBean {

    private String searchCriteria;

    private Hits hits;

    private static Logger logger = Logger.getAnonymousLogger();

    public Hits getHits() {
        return hits;
    }

    public String getSearchCriteria() {
        return searchCriteria;
    }

    public void setSearchCriteria(String searchCriteria) {
        this.searchCriteria = searchCriteria;
    }

    public String search() {
        try {
            Directory directory = FSDirectory.getDirectory(System.getProperty("java.io.tmpdir") + "/index", false);
            IndexSearcher indexSearcher = new IndexSearcher(directory);
            logger.info("JV: Search Parameter = " + searchCriteria);

            Query query = null;
            try {
                QueryParser parser = new QueryParser("description", new StandardAnalyzer());
                query = parser.parse(searchCriteria);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            hits = indexSearcher.search(query);
        } catch (IOException e) {
            e.printStackTrace();
            return "failure";
        }
        logger.info("Hits = " + hits.length());
        return "success";
    }
}
